package com.me.bbs.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.me.bbs.anno.RequireLogin;
import com.me.bbs.common.AuthUtils;
import com.me.bbs.common.Resp;
import com.me.bbs.dto.CommentDTO;
import com.me.bbs.dto.PostDTO;
import com.me.bbs.dto.SubCommentDTO;
import com.me.bbs.entity.Comment;
import com.me.bbs.service.ICommentLikeService;
import com.me.bbs.service.ICommentService;
import com.me.bbs.vo.CommentVO;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.sql.SQLException;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lm
 * @since 2023-01-09
 */
@RestController
@RequestMapping("/comment")
public class CommentController {
    @Resource
    ICommentService commentService;


    @PostMapping("/create")
    @RequireLogin
    public Resp<?> save(@RequestBody CommentVO commentVO, HttpSession session) throws SQLException {
        AuthUtils.checkBan(commentVO.getForum());
        Long userId = (Long) session.getAttribute("user");
        commentVO.setAuthor(userId);
        Long cid = commentService.saveOne(commentVO);
        if (commentVO.getType() == 0) {
            CommentDTO commentById = commentService.getCommentById(cid);
            return Resp.success(commentById, "成功");
        } else {
            SubCommentDTO commentById = commentService.getCommentById(cid, true);
            return Resp.success(commentById, "成功");
        }
    }

    @PostMapping("/getCommentsPage")
    public Resp<?> getCommentsPage(@RequestBody Map<String, Object> map) {
        Integer current = (Integer) map.get("current");
        Integer size = (Integer) map.get("size");
        Long postId = Long.parseLong((String) map.get("postId"));
        //从cid开始加载评论
        Long startFrom =  map.get("cid") == null? null : Long.parseLong((String) map.get("cid"));
        Page<CommentDTO> commentDTOPage = new Page<>(current, size);
        commentDTOPage = commentService.getByPostInPage(commentDTOPage, postId, startFrom);
        return Resp.success(commentDTOPage, "成功");
    }

    @DeleteMapping("/{id}")
    @RequireLogin
    public Resp<?> deleteComment(@PathVariable("id") String idStr) throws SQLException {
        Long id = Long.parseLong(idStr);
        commentService.deleteByCid(id);
        return Resp.success();
    }
}
